import { message } from "ant-design-vue";
import store from "@/store";
import router from "@/router";
import { settingConfig } from '@/config'

export const failAuth = () => {
    store.dispatch('user/logout').then(() => {
        router.replace({
            name: settingConfig.loginName
        })
    })
};

export const failCodeMap = new Map([
    [400, { msg: "请求错误" }],
    [401, { msg: "未认证", handler: failAuth }],
    [403, { msg: "未授权" }],
    [404, { msg: "请求地址错误" }],
    [405, { msg: "请求方式错误" }],
    [408, { msg: "请求超时" }],
    [422, { msg: "验证错误" }],
    [500, { msg: "服务器内部错误" }],
    [501, { msg: "服务未实现" }],
    [502, { msg: "网关错误" }],
    [503, { msg: "服务不可用" }],
    [504, { msg: "网关超时" }],
    [505, { msg: "HTTP版本不受支持" }],
]);

export const handlerErrorCode = (error) => {
    if(!error.response) return Promise.reject(new Error('网络异常或其他错误'));
    const { status } = error.response;
    const { msg, handler } = failCodeMap.get(status);
    message.error(msg);
    if (handler && typeof handler === "function") handler();
    return Promise.reject(error.response);
};

export const handlerSucessResponse = (response) => {
    return response
};
